'use strict'
const fs = require('fs')
const path = require('path')

let mydebug = require('./mydebug');
let controller = require('./controllers/controller');

var mosca = require('mosca');


var settings = {
    port: 1883,
};

var server = new mosca.Server(settings);

server.on('clientConnected', function (client) {
    mydebug.LogOutput('client connected', client.id);
});

// fired when a message is received
server.on('published', function (packet, client) {
    // mydebug.LogOutput('Published', packet.payload);
});

server.on('ready', setup);

function authenticate(client, username, password, callback) {
    var authorized = (username === 'test' && password.toString() === 'test');
    if (authorized) {
        client.user = username;
    }

    callback(null, authorized);
}
// fired when the mqtt server is ready
function setup() {
    server.authenticate = authenticate;
    mydebug.LogOutput('Mosca server is up and running');
}

// client
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://localhost', {username: 'test', password: 'test'});

function remote_cmd(err, granted) {

}

client.on('connect', function () {
    console.log("Connected.");
    client.subscribe('cmd', remote_cmd);
})

function RoLevelChange(level) {
    if (client.connected) {
        client.publish('rolevel', level.toString());
    }
}

function SubLevelChange(level) {
    if (client.connected) {
        client.publish('sublevel', level.toString());
    }
}

function TemperatureChange(temp) {
    if (client.connected) {
        temp = temp / 100.00;
        client.publish('temperature', temp.toFixed(2));
    }
}

controller.ControllerEvent.on("rolevel", RoLevelChange);
controller.ControllerEvent.on("sublevel", SubLevelChange);
controller.ControllerEvent.on("temperature", TemperatureChange);



